package com.neusoft.hifly.lock.strategy.impl;

import org.apache.commons.lang3.StringUtils;
import org.redisson.config.Config;

import com.neusoft.hifly.lock.config.RedissonConfig;
import com.neusoft.hifly.lock.constant.GlobalConstant;
import com.neusoft.hifly.lock.strategy.RedissonConfigService;
import com.neusoft.hifly.lock.utils.Log;

/**
 * 哨兵集群部署Redis连接配置
 */
public class SentineConfigImpl implements RedissonConfigService {

	/**
	 * 根据不同的Redis配置策略创建对应的Config
	 *
	 * @param redissonProperties
	 *            redisson配置
	 * @return Config
	 */
	@Override
	public Config createRedissonConfig(final RedissonConfig redissonProperties) {
		final Config config = new Config();
		try {
			final String address = redissonProperties.getAddress();
			final String password = redissonProperties.getPassword();
			final int database = redissonProperties.getDatabase();
			final String[] addrTokens = address.split(",");
			final String sentinelAliasName = addrTokens[0];
			//设置redis配置文件sentinel.conf配置的sentinel别名
			config.useSentinelServers().setMasterName(sentinelAliasName);
			config.useSentinelServers().setDatabase(database);
			if (StringUtils.isNotBlank(password)) {
				config.useSentinelServers().setPassword(password);
			}
			//设置sentinel节点的服务IP和端口
			for (int i = 1; i < addrTokens.length; i++) {
				config.useSentinelServers()
						.addSentinelAddress(GlobalConstant.REDIS_CONNECTION_PREFIX.getConstantValue() + addrTokens[i]);
			}
			Log.info("初始化[哨兵部署]方式Config,redisAddress:" + address);
		} catch (final Exception e) {
			Log.info("哨兵部署 Redisson init error", e);
		}
		return config;
	}
}
